package com.wb.adutils.ads.gmad

import android.app.Activity
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.RelativeLayout
import com.bytedance.msdk.api.AdError
import com.bytedance.msdk.api.v2.GMAdSize
import com.bytedance.msdk.api.v2.ad.banner.GMBannerAd
import com.bytedance.msdk.api.v2.ad.banner.GMBannerAdListener
import com.bytedance.msdk.api.v2.ad.banner.GMBannerAdLoadCallback
import com.bytedance.msdk.api.v2.slot.GMAdOptionUtil
import com.bytedance.msdk.api.v2.slot.GMAdSlotBanner
import com.wb.adutils.AdBaseLoader
import com.wb.adutils.db.AdEntity
import com.wb.adutils.tools.AdConstants
import com.wb.adutils.tools.LogC
import java.lang.Exception


class GMBannerAdUtils(val adEntity: AdEntity?): AdBaseLoader(adEntity) {

    private var adView: View? = null
    private var mTTBannerViewAd: GMBannerAd? = null

    override fun excLoadAd(activity: Activity) {
        try {
            // 判断当前是否存在config 配置 ，如果存在直接加载广告 ，如果不存在则注册config加载回调
            LogC.e("banner ->  准备加载广告")

            if (isAdLoadSuccess && adView != null) {
                listener?.onAdLoaded(null)
                return
            }

            // 当在banner中混出信息流时，该设置用于信息流相关的设置，例如gdt的设置如下：
            // 针对Gdt Native自渲染广告，可以自定义gdt logo的布局参数。该参数可选,非必须。
            val gdtNativeAdLogoParams = FrameLayout.LayoutParams(width, height, Gravity.CENTER)
            val adGDTOption = GMAdOptionUtil.getGMAdSlotGDTOption()
                .setNativeAdLogoParams(gdtNativeAdLogoParams)
                .build()

            val slotBanner = GMAdSlotBanner.Builder()
                .setBannerSize(GMAdSize.BANNER_CUSTOME)
                .setImageAdSize(width, height) // GMAdSize.BANNER_CUSTOME可以调用setImageAdSize设置大小
                .setAllowShowCloseBtn(false) //如果广告本身允许展示关闭按钮，这里设置为true就是展示。注：目前只有mintegral支持。
                .setBidNotify(true)
                .setMuted(true)
                .setGMAdSlotGDTOption(adGDTOption)
                .setMuted(true) // 控制视频是否静音
                .build()

            mTTBannerViewAd = GMBannerAd(activity, adEntity?.adUnit)
            mTTBannerViewAd?.setAdBannerListener(object : GMBannerAdListener {
                override fun onAdOpened() {
                    /**
                     * 当广告打开浮层时调用，如打开内置浏览器、内容展示浮层，一般发生在点击之后,常常在onAdLeftApplication之前调用，
                     * 不能保证每次都回调 admob sdk和优量汇sdk支持，穿山甲SDK、unity SDK,baidu SDK,mintegral SDK暂时不支持
                     */
                }

                override fun onAdLeftApplication() {
                    /**
                     * 此方法会在用户点击打开其他应用（例如 Google Play）时于 onAdOpened() 之后调用，从而在后台运行当前应用，
                     * 不能保证每次都回调 admob sdk、优量汇sdk、mintegral SDK支持，穿山甲SDK、unity SDK,baidu SDK,暂时不支持
                     */
                }

                override fun onAdClosed() {
                    LogC.e("banner ->  onAdClosed...")
                    listener?.onAdComplete()
                    release()

                }

                override fun onAdClicked() {
                    listener?.onAdClicked()
                }

                override fun onAdShow() {
                    LogC.e("banner ->  onAdShow...")
                    listener?.onAdDisplay()
                }

                override fun onAdShowFail(p0: AdError) {
                    LogC.e("banner ->  onAdShowFail..." + p0.message)
                    listener?.onAdLoadFail(p0.code)
                    release()
                }

            })

            mTTBannerViewAd?.loadAd(slotBanner, object : GMBannerAdLoadCallback {

                override fun onAdFailedToLoad(adError: AdError) {
                    LogC.e("banner ->  onAdFailedToLoad..." + adError.message)
                    excAdLoadFail(adError.code)
                }

                override fun onAdLoaded() {
                    if (timeoutDisposable?.isDisposed == true) { // 已超时
                        LogC.e("banner ->  onAdLoaded...但已超时")
                        return
                    }
                    LogC.e("banner ->  onAdLoaded...")
                    timeoutDisposable?.dispose()
                    adView = mTTBannerViewAd?.bannerView
                    if (adView == null) {
                        LogC.e("banner ->  onAdLoaded...adView is null")
                        listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_INTERNAL)
                        release()
                    } else {
                        isAdLoadSuccess = true
                        listener?.onAdLoaded(mTTBannerViewAd)
                    }
                }
            })
            isAdLoadSuccess = false
        } catch (e: Exception) {
            e.printStackTrace()
            timeoutDisposable?.dispose()
            listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_EXCEPTION)
            release()
        }
    }

    override fun onResume(){
        mTTBannerViewAd?.onResume()
    }

    override fun onPause(){
        mTTBannerViewAd?.onPause()
    }

    override fun showAd(adRoot: ViewGroup?){
        LogC.e("banner ->  showAd...")
        if (adRoot == null || adRoot.context == null) {
            release()
            LogC.e("banner ->  showAd...adRoot is null")
            return
        }

        adRoot.removeAllViews()
        if (!isAdLoadSuccess) {
            LogC.e("banner ->  showAd isAdLoadSuccess is false...")
            adRoot.visibility = View.GONE
            listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_NOT_LOAD_SUCCESS)
            release()
            return
        }
        LogC.e("banner ->  showAd  添加到view...")
        adRoot.visibility = View.VISIBLE
        val layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT)
        adRoot.addView(adView, layoutParams)
    }



    override fun release(){
        super.release()
        mTTBannerViewAd?.destroy()
        mTTBannerViewAd = null
        adView = null
    }
}

